#include "esp_lvgl_port.h"
#include "esp_log.h"
#include "ac_control_ui.h"
#include "ir_air_conditioner.h"
#include "main_ui.h"
#include "ui_setting.h"
#include "md_images.h"
#include "func_pin_image.h"
#include "md_languages.h"
#include "pin_config.h"

// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);

// 控件指针
static lv_obj_t *temp_dropdown;
static lv_obj_t *power_switch;
static lv_obj_t *mode_dropdown;
static lv_obj_t *fan_dropdown;
static lv_obj_t *device_dropdown;
static lv_obj_t *send_btn;
static lv_obj_t *app_list = NULL;

// 全局变量
static bool circular_scroll = true; // 弧形滚动效果开关


void exit_ac_control_ui(lv_obj_t *root)
{
    switch_to_main_screen(); // 切换到主界面
    lv_obj_del(root);
}

// 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);
        // 右划或上划退出
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            lv_obj_t *root = lv_event_get_target(e);
            exit_ac_control_ui(root);
        }
    }
}

// 发送按钮回调
static void send_btn_cb(lv_event_t *e)
{
    // 获取当前选择的值
    uint16_t temp_sel = lv_dropdown_get_selected(temp_dropdown);
    uint16_t mode_sel = lv_dropdown_get_selected(mode_dropdown);
    uint16_t fan_sel = lv_dropdown_get_selected(fan_dropdown);
    uint16_t device_sel = lv_dropdown_get_selected(device_dropdown);
    bool power_state = lv_obj_has_state(power_switch, LV_STATE_CHECKED);

    // 根据设备选择确定协议
    ir_protocol_t protocol;
    switch (device_sel) {
        case 0:
            protocol = NEC_PROTOCOL;
            break;
        case 1:
            protocol = HAIER_YRW02_PROTOCOL;
            break;
        case 2:
            protocol = MIDEA_R05D_PROTOCOL;
            break;
        default:
            protocol = MIDEA_R05D_PROTOCOL;
            break;
    }

    // 初始化空调控制模块
    pAir_conditioner_t pAC = ir_air_conditioner_init(protocol, MDLINK_IR_TX_IO);

    // 设置空调参数
    air_conditioner_set_power(pAC, power_state);
    air_conditioner_set_temp(pAC, temp_sel + 16); // 16-30度

    // 设置模式
    air_conditioner_set_mode(pAC, mode_sel);

    // 设置风速
    air_conditioner_set_fan(pAC, fan_sel);

    // 发送指令
    air_conditioner_send(pAC);

    // 延迟并清理
    vTaskDelay(pdMS_TO_TICKS(100));
    air_conditioner_del(pAC);

    ESP_LOGI("AC_UI", "发送指令: 协议=%d, 温度=%d, 模式=%d, 风速=%d, 电源=%s",
             protocol, temp_sel + 16, mode_sel, fan_sel, power_state ? "开" : "关");
}

// 语音控制开关回调
static void ac_power_event_cb(lv_event_t *e)
{
    lv_obj_t *sw = lv_event_get_target(e);
    bool state = lv_obj_has_state(sw, LV_STATE_CHECKED);
    // 这里可以添加语音控制逻辑
    ESP_LOGI("AC_UI", "电源状态改变: %s", state ? "开" : "关");
}

// 设备类型下拉框回调
static void device_type_dd_event_cb(lv_event_t *e)
{
    lv_obj_t *dropdown = lv_event_get_target(e);
    uint16_t sel = lv_dropdown_get_selected(dropdown);
    ESP_LOGI("AC_UI", "设备类型改变: %d", sel);
}

// 温度下拉框回调
static void temp_dd_event_cb(lv_event_t *e)
{
    lv_obj_t *dropdown = lv_event_get_target(e);
    uint16_t sel = lv_dropdown_get_selected(dropdown);
    ESP_LOGI("AC_UI", "温度改变: %d", sel + 16);
}

// 模式下拉框回调
static void mode_dd_event_cb(lv_event_t *e)
{
    lv_obj_t *dropdown = lv_event_get_target(e);
    uint16_t sel = lv_dropdown_get_selected(dropdown);
    ESP_LOGI("AC_UI", "模式改变: %d", sel);
}

// 风速下拉框回调
static void fan_dd_event_cb(lv_event_t *e)
{
    lv_obj_t *dropdown = lv_event_get_target(e);
    uint16_t sel = lv_dropdown_get_selected(dropdown);
    ESP_LOGI("AC_UI", "风速改变: %d", sel);
}

// 弧形滚动效果
static void lv_demo_smartwatch_scroll_event(lv_event_t *e)
{
    // 获取事件类型
    lv_event_code_t event_code = lv_event_get_code(e);

    // 只处理滚动事件，其他事件直接返回
    if (event_code != LV_EVENT_SCROLL)
        return;

    // 获取触发事件的滚动列表对象
    lv_obj_t *list = lv_event_get_target(e);
    if (!list)
        return;

    // 获取列表的坐标区域
    lv_area_t list_a;
    lv_obj_get_coords(list, &list_a);

    // 计算列表垂直中心点坐标
    lv_coord_t list_y_center = list_a.y1 + lv_area_get_height(&list_a) / 2;

    // 设置弧形滚动的半径（列表高度的60%）
    lv_coord_t r = lv_obj_get_height(list) * 6 / 10;

    // 获取列表中的子对象数量
    uint32_t child_cnt = lv_obj_get_child_cnt(list);

    // 遍历所有子对象
    for (uint32_t i = 0; i < child_cnt; i++) {
        lv_obj_t *child = lv_obj_get_child(list, i);
        if (!child)
            continue;

        // 确保对象是基础lv_obj类型（过滤非基础对象）
        if (!lv_obj_has_class(child, &lv_obj_class))
            continue;

        // 获取子对象的坐标区域
        lv_area_t child_a;
        lv_obj_get_coords(child, &child_a);

        // 计算子对象垂直中心点坐标
        lv_coord_t child_y_center = child_a.y1 + lv_area_get_height(&child_a) / 2;

        // 计算子对象与列表中心的垂直距离（绝对值）
        lv_coord_t diff_y = LV_ABS(child_y_center - list_y_center);

        // 计算子对象的水平偏移量（用于弧形效果）
        lv_coord_t x;
        if (diff_y >= r) {
            // 当距离超过半径时，使用最大偏移量（半径值）
            x = r;
        } else {
            // 应用圆形公式计算偏移：x = r - sqrt(r² - dy²)
            uint32_t x_sqr = (uint32_t)(r * r) - (uint32_t)(diff_y * diff_y);
            lv_sqrt_res_t res;            // 平方根计算结果结构体
            lv_sqrt(x_sqr, &res, 0x8000); // 计算平方根（使用Q15格式的定点数）
            x = r - res.i;                // 计算实际偏移值
        }

        // 安全更新子对象位置：
        // 1. 先删除现有的平移动画（避免冲突）
        lv_anim_del(child, (lv_anim_exec_xcb_t)lv_obj_set_style_translate_x);

        // 2. 设置新的水平偏移（根据circular_scroll标志决定是否启用弧形效果）
        lv_obj_set_style_translate_x(child, circular_scroll ? x : 0, LV_STATE_DEFAULT);
    }
}

static void add_item(const char *setting_name, int index, char *icon_symbol)
{
    lv_obj_t *panel = lv_obj_create(app_list);
    if (!panel)
        return;

    // 设置面板大小并去除所有边距
    lv_obj_set_size(panel, lv_pct(100), 64);
    lv_obj_clear_flag(panel, LV_OBJ_FLAG_SCROLLABLE);

    // 面板样式 - 去除所有边距和内边距
    lv_obj_set_style_pad_all(panel, 0, LV_PART_MAIN);
    // 修复后（正确）

    // lv_obj_set_style_margin_top(panel, 0, LV_PART_MAIN);
    // lv_obj_set_style_margin_bottom(panel, 0, LV_PART_MAIN);
    // lv_obj_set_style_margin_left(panel, 0, LV_PART_MAIN);
    // lv_obj_set_style_margin_right(panel, 0, LV_PART_MAIN);
    lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
    lv_obj_set_style_bg_color(panel, lv_color_hex(get_screen_color_val()), 0);
    //lv_obj_set_style_border_color(panel, lv_color_white(), 0);
    lv_obj_set_style_border_opa(panel, LV_OPA_COVER, 0);
    lv_obj_set_style_border_width(panel, 1, 0);
    lv_obj_set_style_border_side(panel, LV_BORDER_SIDE_BOTTOM, 0);
    lv_obj_set_style_radius(panel, 0, 0);
    lv_obj_set_style_text_font(panel, &myFont, 0);

    // 创建图标 - 使用图片控件
    lv_obj_t *icon = lv_img_create(panel);
    lv_img_set_src(icon, icon_symbol);           // 设置图片源
    lv_obj_set_size(icon, 32, 32);               // 设置图标大小
    lv_obj_align(icon, LV_ALIGN_LEFT_MID, 5, 0); // 左侧对齐，左边距5px

    // 设置名称标签 - 紧挨着图标
    lv_obj_t *label = lv_label_create(panel);
    if (label) {
        lv_obj_set_style_text_color(label, get_btn_font_color(), 0);
        lv_label_set_text(label, setting_name);
        lv_obj_align_to(label, icon, LV_ALIGN_OUT_RIGHT_MID, 7, 0); // 图标右侧10px
    }
    // 根据索引创建不同类型的控件
    switch (index) {
        case AC_DEVICE_TYPE_NUM: { // 设备类型
            device_dropdown = lv_dropdown_create(panel);
            lv_dropdown_set_options(device_dropdown, "NEC\n海尔\n美的");
            lv_obj_set_width(device_dropdown, 100);
            lv_obj_align(device_dropdown, LV_ALIGN_RIGHT_MID, -10, 0); // 右侧对齐，右边距5px
            lv_obj_add_event_cb(device_dropdown, device_type_dd_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
            // 设置默认选中的设备
            lv_dropdown_set_selected(device_dropdown, 2); // 默认选中美的设备
            break;
        }
        case AC_TEMP_NUM: { // 温度下拉框
            temp_dropdown = lv_dropdown_create(panel);
            lv_dropdown_set_options(temp_dropdown, "16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30");
            lv_obj_set_width(temp_dropdown, 100);
            lv_obj_align(temp_dropdown, LV_ALIGN_RIGHT_MID, -10, 0); // 右侧对齐，右边距5px
            lv_obj_add_event_cb(temp_dropdown, temp_dd_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
            // 设置默认温度
            lv_dropdown_set_selected(temp_dropdown, 8); // 默认24度
            break;
        }
        case AC_POWER_NUM: { // 电源控制开关
            power_switch = lv_switch_create(panel);
            lv_obj_align(power_switch, LV_ALIGN_RIGHT_MID, -10, 0); // 右侧对齐，右边距5px
            lv_obj_add_state(power_switch, LV_STATE_CHECKED);       // 默认开启
            lv_obj_add_event_cb(power_switch, ac_power_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
            break;
        }
        case AC_MODE_NUM: { // 模式下拉框
            mode_dropdown = lv_dropdown_create(panel);
            lv_dropdown_set_options(mode_dropdown, "自动\n制冷\n除湿\n制热\n送风");
            lv_obj_set_width(mode_dropdown, 100);
            lv_obj_align(mode_dropdown, LV_ALIGN_RIGHT_MID, -10, 0); // 右侧对齐，右边距5px
            lv_obj_add_event_cb(mode_dropdown, mode_dd_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
            // 设置默认模式
            lv_dropdown_set_selected(mode_dropdown, 1); // 默认制冷模式
            break;
        }
        case AC_FAN_NUM: { // 风速下拉框
            fan_dropdown = lv_dropdown_create(panel);
            lv_dropdown_set_options(fan_dropdown, "自动\n低\n中\n高");
            lv_obj_set_width(fan_dropdown, 100);
            lv_obj_align(fan_dropdown, LV_ALIGN_RIGHT_MID, -10, 0); // 右侧对齐，右边距5px
            lv_obj_add_event_cb(fan_dropdown, fan_dd_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
            // 设置默认风速
            lv_dropdown_set_selected(fan_dropdown, 2); // 默认中风速
            break;
        }
    }
}

/* 
 * @brief:创建空调控制界面
 */
lv_obj_t *create_ac_control_ui(void)
{
    lv_obj_t *root = lv_obj_create(NULL);
    if (!root)
        return NULL;

    lv_obj_set_size(root, LV_PCT(100), LV_PCT(100));
    uint32_t color = get_screen_color_val();
    lv_obj_set_style_bg_color(root, lv_color_hex(color), 0);
    lv_obj_clear_flag(root, LV_OBJ_FLAG_SCROLLABLE);

    // 使根对象可点击以接收手势事件
    lv_obj_add_flag(root, LV_OBJ_FLAG_CLICKABLE);
    lv_obj_add_event_cb(root, event_handler, LV_EVENT_GESTURE, root);

    // 创建标题
    lv_obj_t *title = lv_label_create(root);
    lv_label_set_text(title, "空调控制");
    lv_obj_set_style_text_color(title, lv_color_white(), LV_PART_MAIN);
    lv_obj_set_style_text_font(title, &myFont, LV_PART_MAIN);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);

    /************************************************************************/
    app_list = lv_obj_create(root);
    if (!app_list) {
        lv_obj_del(root);
        return NULL;
    }

    lv_obj_set_style_bg_color(app_list, lv_color_hex(color), 0);
    lv_obj_set_size(app_list, lv_pct(100), lv_pct(100));
    lv_obj_align(app_list, LV_ALIGN_CENTER, 0, 20);
    lv_obj_set_scroll_dir(app_list, LV_DIR_VER);
    lv_obj_set_scrollbar_mode(app_list, LV_SCROLLBAR_MODE_OFF);
    lv_obj_set_flex_flow(app_list, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(app_list, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);

    // 允许事件冒泡
    lv_obj_add_flag(app_list, LV_OBJ_FLAG_GESTURE_BUBBLE);
    lv_obj_clear_flag(app_list, LV_OBJ_FLAG_CLICKABLE);

    // 列表样式
    lv_obj_set_style_bg_opa(app_list, LV_OPA_COVER, 0);
    lv_obj_set_style_pad_top(app_list, 10, 0);    // 减少顶部内边距
    lv_obj_set_style_pad_bottom(app_list, 10, 0); // 减少底部内边距
    lv_obj_set_style_border_width(app_list, 0, 0);

    // 添加设置项
    add_item(get_func_txt_data(FUNC_AC_CONTROL, AC_DEVICE_TYPE_NUM), AC_DEVICE_TYPE_NUM, get_func_image_data(FUNC_AC_CONTROL, AC_DEVICE_TYPE_NUM));
    add_item(get_func_txt_data(FUNC_AC_CONTROL, AC_TEMP_NUM), AC_TEMP_NUM, get_func_image_data(FUNC_AC_CONTROL, AC_TEMP_NUM));
    add_item(get_func_txt_data(FUNC_AC_CONTROL, AC_POWER_NUM), AC_POWER_NUM, get_func_image_data(FUNC_AC_CONTROL, AC_POWER_NUM));
    add_item(get_func_txt_data(FUNC_AC_CONTROL, AC_MODE_NUM), AC_MODE_NUM, get_func_image_data(FUNC_AC_CONTROL, AC_MODE_NUM));
    add_item(get_func_txt_data(FUNC_AC_CONTROL, AC_FAN_NUM), AC_FAN_NUM, get_func_image_data(FUNC_AC_CONTROL, AC_FAN_NUM));


    lv_obj_add_event_cb(app_list, lv_demo_smartwatch_scroll_event, LV_EVENT_SCROLL, NULL);
    lv_obj_t *btn = lv_btn_create(root);
    lv_obj_set_size(btn, lv_pct(100), lv_pct(20));
    lv_obj_align(btn, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_set_style_bg_color(btn, lv_color_hex(0x0066CC), LV_PART_MAIN);

    lv_obj_t *btn_label = lv_label_create(btn);
    lv_label_set_text(btn_label, "发送指令");
    lv_obj_set_style_text_font(btn_label, &myFont, LV_PART_MAIN);
    lv_obj_set_style_text_color(btn_label, lv_color_white(), LV_PART_MAIN);
    lv_obj_center(btn_label);

    lv_obj_add_event_cb(btn, send_btn_cb, LV_EVENT_CLICKED, NULL);
    // 设置滚动捕捉
    lv_obj_set_scroll_snap_y(app_list, LV_SCROLL_SNAP_CENTER);

    return root;
    }